package com.atguigu.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.to.SeckillOrderTO;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVO;
import com.atguigu.gulimall.seckill.feign.CouponFeignService;
import com.atguigu.gulimall.seckill.feign.ProductFeignService;
import com.atguigu.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.atguigu.gulimall.seckill.service.SeckillService;
import com.atguigu.gulimall.seckill.to.SeckillSkuRedisTO;
import com.atguigu.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.atguigu.gulimall.seckill.vo.SkuInfoVO;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.print.DocFlavor;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;


@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    CouponFeignService couponFeignService;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    RabbitTemplate rabbitTemplate;

    private final String SESSION_CACHE_PREFIX = "seckill:sessions:";
    private final String SKUKILL_CACHE_PREFIX = "seckill:sku:";
    private final String SKU_STOCK_SEMAPHORE = "seckill:stock:";//+商品随机码

    //TODO 未完成逻辑（上架秒杀商品时要锁定库存数量，活动结束后再解锁）
    @Override
    public void uploadSeckillSkuLast3Days() {
        //扫描最近三天需要参与秒杀的活动
        R session = couponFeignService.getLast3DaySession();
        if (session.getCode() == 0) {
            //上架商品
            List<SeckillSessionWithSkus> sessionDataList = session.getData(new TypeReference<List<SeckillSessionWithSkus>>() {
            });
            //缓存到redis
            saveSessionInfos(sessionDataList);
            //缓存活动的关联商品信息
            saveSessionSkuInfos(sessionDataList);
        }
    }

    @Override
    public List<SeckillSkuRedisTO> getCurrentSeckillSkus() {
        //确定当前时间属于哪个秒杀场次
        long time = new Date().getTime();
        Set<String> keys = redisTemplate.keys(SESSION_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSION_CACHE_PREFIX, "");
            String[] s = replace.split("_");
            long start = Long.parseLong(s[0]);
            long end = Long.parseLong(s[1]);
            if (time >= start && time <= end) {
                //获取这个秒杀场次需要的所有商品信息
                List<String> range = redisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
                List<String> list = hashOps.multiGet(range);
                if (list != null) {
                    List<SeckillSkuRedisTO> collect = list.stream().map(item -> {
                        SeckillSkuRedisTO redisTO = JSON.parseObject(item, SeckillSkuRedisTO.class);
                        //当前秒杀开始就需要随机码
//                        redisTO.setRandomCode(null);
                        return redisTO;
                    }).collect(Collectors.toList());
                    return collect;
                }
                break;
            }
        }

        return null;
    }

    @Override
    public SeckillSkuRedisTO getSkuSeckillInfo(Long skuId) {
        //找到所有需要参与秒杀的商品的key
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        //使用正则表达式匹配所有key
        String regx = "\\d_" + skuId;
        Set<String> keys = hashOps.keys();
        for (String key : keys) {
            if (Pattern.matches(regx, key)) {
                String json = hashOps.get(key);
                SeckillSkuRedisTO redisTO = JSON.parseObject(json, SeckillSkuRedisTO.class);
                //秒杀未开始删除随机码
                long current = new Date().getTime();
                if (current < redisTO.getStartTime() || current > redisTO.getEndTime()) {
                    redisTO.setRandomCode(null);
                }
                return redisTO;
            }
        }

        return null;
    }

    //TODO 未完成逻辑（1、上架秒杀商品时每个数据都有过期时间  2、秒杀后续流程简化了收获地址等信息）
    @Override
    public String kill(String killId, String key, Integer num) {
        MemberRespVO respVO = LoginUserInterceptor.threadLocal.get();
        //获取当前秒杀商品的详细信息
        BoundHashOperations<String, String, String> hashOps = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
        String json = hashOps.get(killId);
        if (!StringUtils.isEmpty(json)) {
            SeckillSkuRedisTO redisTO = JSON.parseObject(json, SeckillSkuRedisTO.class);
            //校验时间合法性
            Long startTime = redisTO.getStartTime();
            Long endTime = redisTO.getEndTime();
            long time = new Date().getTime();
            if (time >= startTime || time <= endTime) {
                //校验随机码和商品id
                String randomCode = redisTO.getRandomCode();
                String skuId = redisTO.getPromotionSessionId() + "_" + redisTO.getSkuId();
                if (randomCode.equals(key) && killId.equals(skuId)) {
                    //验证购物数量是否合理
                    if (num <= redisTO.getSeckillLimit()) {
                        //验证这个人是否已经购买过，幂等性；只要秒杀成功就占位 userId_sessionId_skuId
                        String redisKey = respVO.getId() + "_" + skuId;
                        //秒杀活动结束后自动过期
                        long ttl = endTime - time;
                        //setIfAbsent()=redis的SENTNX命令：只有KEY不存在才能存入
                        Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(redisKey, num.toString(), ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean) {
                            //占位成功说明从来没买过
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + randomCode);
                            //获取信号量，为了不阻塞，获取不到则秒杀失败
                            String orderSn = IdWorker.getTimeId();
                            boolean b = semaphore.tryAcquire(num);
                            if (b) {
                                //秒杀成功，发送下单消息到MQ
                                SeckillOrderTO orderTO = new SeckillOrderTO();
                                orderTO.setOrderSn(orderSn);
                                orderTO.setMemberId(respVO.getId());
                                orderTO.setNum(num);
                                orderTO.setPromotionSessionId(redisTO.getPromotionSessionId());
                                orderTO.setSkuId(redisTO.getSkuId());
                                orderTO.setSeckillPrice(redisTO.getSeckillPrice());
                                rabbitTemplate.convertAndSend("order-event-exchange", "order.seckill", orderTO);
                                return orderSn;
                            }


                        }
                    }
                }
            }
        }
        return null;
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> sessionDataList) {
        sessionDataList.stream().forEach(session -> {
            //准备hash操作
            BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            session.getRelationSkus().stream().forEach(seckillSkuVO -> {
                //随机码
                String token = UUID.randomUUID().toString().replaceAll("-", "");

                //判断redis中是否存在key，避免重复缓存
                Boolean checkKey = ops.hasKey(seckillSkuVO.getPromotionSessionId() + "_" + seckillSkuVO.getSkuId().toString());
                if (!checkKey) {
                    //缓存商品
                    SeckillSkuRedisTO redisTO = new SeckillSkuRedisTO();
                    //sku的秒杀信息
                    BeanUtils.copyProperties(seckillSkuVO, redisTO);
                    //sku的基本数据
                    R skuInfo = productFeignService.getSkuInfo(seckillSkuVO.getSkuId());
                    if (skuInfo.getCode() == 0) {
                        SkuInfoVO info = skuInfo.getData("skuInfo", new TypeReference<SkuInfoVO>() {
                        });
                        redisTO.setSkuInfo(info);
                    }
                    //设置当前商品的秒杀时间信息
                    redisTO.setStartTime(session.getStartTime().getTime());
                    redisTO.setEndTime(session.getEndTime().getTime());
                    //放入随机码
                    redisTO.setRandomCode(token);
                    //放入缓存
                    ops.put(seckillSkuVO.getPromotionSessionId() + "_" + seckillSkuVO.getSkuId().toString(), JSON.toJSONString(seckillSkuVO));

                    //引入redisson分布式信号量，限流作用
                    RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORE + token);
                    //设置库存，商品秒杀的数量作为信号量
                    semaphore.trySetPermits(seckillSkuVO.getSeckillCount());
                }

            });
        });

    }

    private void saveSessionInfos(List<SeckillSessionWithSkus> sessionDataList) {
        sessionDataList.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = SESSION_CACHE_PREFIX + startTime + endTime;
            //判断redis中是否存在key，避免重复缓存商品
            Boolean hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                //缓存商品信息
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId() + "_" + item.getSkuId().toString()).collect(Collectors.toList());
                redisTemplate.opsForList().leftPushAll(key, collect);
            }
        });


    }
}
